import ajax from '@/utils/ajax';
import { push } from 'connected-react-router';
import { call, put, takeEvery, } from 'redux-saga/effects';

function* login(action) {
  try {
    const loginResult = yield call(ajax, {
      method: 'post',
      url: '/api/login',
      data: action.payload,
    });
    yield put({
      type: 'LOGIN_SUCCESS',
      payload: loginResult,
    });
    sessionStorage.setItem('isLogin', 'true');
    sessionStorage.setItem('loginUser', JSON.stringify(loginResult.data));
    yield put({
      type: 'FETCH_MENU',
      payload: loginResult.data.id,
    })
    yield put(push('/home'));
  } catch (e) {
    console.error(e);
    yield put({
      type: 'LOGIN_FAILED',
      payload: e.message,
    });
  }
}

function* logout(action) {
  try {
    const logoutResult = yield call(ajax, {
      method: 'post',
      url: '/api/logout',
      data: action.payload,
    });
    yield put({
      type: 'LOGOUT_SUCCESS',
      payload: logoutResult,
    });
    sessionStorage.removeItem('isLogin');
    sessionStorage.removeItem('loginUser');
    yield put(push('/login'));
  } catch (e) {
    console.error(e);
    yield put({
      type: 'LOGOUT_FAILED',
      payload: e.message,
    });
  }
}


function* fetchMenu(action) {
  const { payload } = action;
  try {
    const menuResult = yield call(ajax, {
      method: 'post',
      url: 'http://localhost:8080/api/menu',
      data: {
        id: payload,
      },
    });
    yield put({
      type: 'SET_MENU',
      payload: menuResult.list,
    });
  } catch (e) {
    console.error(e);
    yield put({
      type: 'FETCH_MENU_FAILED',
      payload: e.message,
    });
  }
}

function* mySaga() {
  yield takeEvery('LOGIN', login);
  yield takeEvery('LOGOUT', logout);
  yield takeEvery('FETCH_MENU', fetchMenu);
}

export default mySaga;
